import core
import math
import copy

model_wrapper=core.model_wrapper
pyfitter=core.pyfitter
#pychisq=core.pychisq
pyvec=core.pyvec
pyleastsq=core.pyleastsq
statistic_holder=[]
pystatistic=core.pystatistic
eval_log=[]

HAVE_X_ERROR=False


class pychisq(pystatistic):
    def __init__(self):
        pystatistic.__init__(self)
        statistic_holder.append(self)
        eval_log=[]
        pass

    def do_get_type_name(self):
        return type(self).__name__

    
    def do_clone(self):
        eval_log=[]
        return self

    def do_destroy(self):
        for i in range(0,len(statistic_holder)):
            if statistic_holder[i] is self:
         #       print 'Loaded model:',model_holder[i],'deleted'
                del statistic_holder[i]
                break

    def do_eval(self,p):
        result=0
        for i in range(0,self.get_data_set().size()-1):
            if HAVE_X_ERROR:
                x1=self.get_data_set().get_data(i).get_x()-self.get_data_set().get_data(i).get_x_lower_err()
                x2=self.get_data_set().get_data(i).get_x()+self.get_data_set().get_data(i).get_x_upper_err()

                errx=(self.eval_model(x1,p)-self.eval_model(x2,p))/2
            else:
                errx=0.
            
            y_model=self.eval_model(self.get_data_set().get_data(i).get_x(),p)
            y_obs=self.get_data_set().get_data(i).get_y()
            y_err=0
            if y_model>y_obs:
                y_err=self.get_data_set().get_data(i).get_y_upper_err()
            else:
                y_err=self.get_data_set().get_data(i).get_y_lower_err()
            
            chi2=(y_obs-y_model)**2/(y_err*y_err+errx*errx)
            result+=chi2
        print result
        point=[]
        for i in range(0,p.size()):
            point.append(p[i])
        point.append(result)
        eval_log.append(point)
        return result

pass


